/*
*  CELabelProtocol.cpp
*  LID Library
*
*  Created by Alexander Trutchenko on 05/11/12.
*  Copyright 2011 League of Independent Developers. All rights reserved.
*
*/


#include "cocos2dx_extentions/labels/CELabelBMFontIME.h"

#include "lid_lib/src/strings_and_localization/LLStringUtils.h"

using namespace cocos2d;
using namespace lidlib;

namespace cocosext{
	
////////////////////////////////////////////////////////
//
/** CELabelBMFontIME
* It is editable variant of CELabelBMFont 
*/
////////////////////////////////////////////////////////

CELabelBMFontIME *CELabelBMFontIME::labelWithString(const wchar_t *str, const char *fntFile)
{
	CELabelBMFontIME *pRet = new CELabelBMFontIME();
	if(pRet && pRet->initWithString(str, fntFile))
	{
		pRet->autorelease();
		return pRet;
	}
	CC_SAFE_DELETE(pRet)
	return NULL;
}



////////////////////////////////////////////////////////
// CELabelBMFont interface
void CELabelBMFontIME::setString(const wchar_t *label)
{
	CELabelBMFont::setString(label);
	_utf8text = utf16_wstring_to_utf8_string(m_sString);
}

////////////////////////////////////////////////////////
// CCIMEDelegate

bool CELabelBMFontIME::attachWithIME()
{
    bool bRet = CCIMEDelegate::attachWithIME();
    if (bRet)
    {
        // open keyboard
        CCEGLView * pGlView = CCDirector::sharedDirector()->getOpenGLView();
        if (pGlView)
        {
            pGlView->setIMEKeyboardState(true);
        }
    }
    return bRet;
}

bool CELabelBMFontIME::detachWithIME()
{
    bool bRet = CCIMEDelegate::detachWithIME();
    if (bRet)
    {
        // close keyboard
        CCEGLView * pGlView = CCDirector::sharedDirector()->getOpenGLView();
        if (pGlView)
        {
            pGlView->setIMEKeyboardState(false);
        }
    }
    return bRet;
}

void CELabelBMFontIME::insertText(const char * text, int len)
{
	std::wstring newStr = m_sString + utf8_string_to_utf16_wstring(std::string(text, len));
	setString(newStr.c_str());
}

void CELabelBMFontIME::deleteBackward()
{
    int nStrLen = _utf8text.length();
    if (! nStrLen)
    {
        // there is no string
        return;
    }

	// get the delete byte number
    int nDeleteLen = 1;    // default, erase 1 byte
    while(0x80 == (0xC0 & _utf8text.at(nStrLen - nDeleteLen)))
    {
        ++nDeleteLen;
    }

	std::wstring newStr = utf8_string_to_utf16_wstring(_utf8text.substr(0, _utf8text.size() - nDeleteLen));
	setString(newStr.c_str());
}

}
